<template>
  <div class="box">
    <el-form ref="loginForm" :model="loginForm" :rules="rules" style="width:400px;" label-width="20%">
      <div class="form-title">登录</div>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="passwd">
        <el-input show-password v-model="loginForm.passwd" placeholder="请输入密码"></el-input>
      </el-form-item>

      <!-- 记住密码复选框 -->
      <el-form-item>
        <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
      </el-form-item>

      <!-- 当前角色和切换角色按钮放在同一行 -->
      <el-form-item label="当前角色">
        <el-row gutter={10}>
          <el-col :span="16">
            <el-input v-model="currentRole" disabled></el-input>
          </el-col>
          <el-col :span="8">
            <el-button @click="toggleRole" type="info" style="width: 100%;">切换角色</el-button>
          </el-col>
        </el-row>
      </el-form-item>

      <!-- 验证码部分 -->
      <el-form-item label="验证码" prop="captcha">
        <div class="captcha-container">
          <span class="captcha-text">{{ captchaText }}</span>
          <el-input v-model="loginForm.captcha" placeholder="请输入验证码" maxlength="6"></el-input>
          <el-button @click="generateCaptcha" type="text">换一个</el-button>
        </div>
      </el-form-item>

      <el-form-item class="button-container">
        <el-button type="primary" @click="login(loginForm)" :loading="loadingbut">登录</el-button>
        <el-button type="danger" @click="cancel">重置</el-button>
        <el-button @click="goToRegisterPage" type="text">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import { loginUser } from '../../src/api/user.js';

export default {
  name: 'LoginView',
  data() {
    return {
      loginForm: {
        username: '',
        passwd: '',
        captcha: '',
        userType: 0
      },
      captchaText: '',  // 用于存储随机生成的验证码
      rememberMe: false,  // 记录用户是否勾选记住密码
      currentRole: '普通用户',  // 默认角色是普通用户
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        passwd: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { validator: this.validateCaptcha, trigger: 'blur' }
        ]
      },
      loadingbut: false,
    };
  },
  methods: {
    // 生成随机字母验证码
    generateCaptcha() {
      const letters = '1';
      let captcha = '';
      for (let i = 0; i < 6; i++) {
        captcha += letters.charAt(Math.floor(Math.random() * letters.length));
      }
      this.captchaText = captcha;
    },
    
    // 验证用户输入的验证码是否正确
    validateCaptcha(rule, value, callback) {
      if (value !== this.captchaText) {
        callback(new Error('验证码不正确'));
      } else {
        callback();
      }
    },

    // 切换角色
    toggleRole() {
      if (this.currentRole === '普通用户') {
        // 切换到普通用户
        this.currentRole = '管理员';
        this.loginForm.userType = '1';
        console.log(this.loginForm.userType)
      } else {
        // 切换到管理员
        this.currentRole = '普通用户';
        this.loginForm.userType = '0';
        console.log(this.loginForm.userType)
      }
    },

    // 登录逻辑
    login(loginForm) {
      this.$refs['loginForm'].validate((valid) => {
        if (valid) {
          // 根据角色进行不同的登录处理
          if (this.currentRole === '管理员') {
            loginUser(loginForm).then(res => {
              if (res.data.code === 200) {
                console.log(res.data.data)
                this.$alert('管理员登录成功', { confirmButtonText: '确定' });
                // 跳转到管理员页面
               // 转成Json格式储存
               localStorage.setItem("user",JSON.stringify(res.data.data))
              
                this.$router.replace('/adminview');
              } else {
                this.$alert('用户名或密码错误！')
              }
            })
            
          } else if (this.currentRole === '普通用户') {
            loginUser(loginForm).then(res => {
              if (res.data.code === 200) {
                console.log(res.data.data)
                this.$alert('普通用户登录成功', { confirmButtonText: '确定' });
                // 转成Json格式储存
                localStorage.setItem("user",JSON.stringify(res.data.data))
                // 跳转到普通用户页面
                this.$router.replace('/home');

              }else{
                this.$alert('用户名或密码错误！')
              }
            })
          } else {
            this.$alert('用户名或密码错误！', { confirmButtonText: '确定' });
            this.loadingbut = false;
            return;
          }

          // 如果勾选了“记住密码”，则将用户名和密码保存在localStorage
          if (this.rememberMe) {
            localStorage.setItem('username', loginForm.username);
            localStorage.setItem('password', loginForm.passwd);
          } else {
            localStorage.removeItem('username');
            localStorage.removeItem('password');
          }
          // 
          localStorage.setItem('username', loginForm.username);
        } else {
          this.$alert('表单验证失败', { confirmButtonText: '确定' });
          return false;
        }
      });
    },

    // 重置表单
    cancel() {
      this.$refs['loginForm'].resetFields();
      this.generateCaptcha(); // 每次重置时重新生成验证码
    },

    // 跳转到注册页面
    goToRegisterPage() {
      this.$router.push('/register');
    }
  },
  created() {
    // 在页面加载时生成一个验证码
    this.generateCaptcha();

    // 如果localStorage中有用户名和密码，自动填充
    const savedUsername = localStorage.getItem('username');
    const savedPassword = localStorage.getItem('passwd');
    
    if (savedUsername && savedPassword) {
      this.loginForm.username = savedUsername;
      this.loginForm.passwd = savedPassword;
      this.rememberMe = true;
    }
  }
};
</script>

<style scoped>
html, body {
  height: 100%;
  margin: 0;
}
.form-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
}
.box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url('../assets/beijing1.png');
  background-size: cover;
  background-position: center;
}
.el-form {
  width: 400px;
  padding: 30px;
  border-radius: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 20px;
}

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-text {
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
  border: 1px solid #ccc;
  padding: 5px;
  background-color: #f5f5f5;
}

.button-container {
  text-align: center;
}

.el-button {
  display: inline-block;
  width: 25%;
  margin-right: 10px;
}

.el-button:last-child {
  margin-right: 0;
}
</style>